import { drizzle } from 'drizzle-orm/better-sqlite3'
import Database from 'better-sqlite3'
import type { BetterSQLite3Database } from 'drizzle-orm/better-sqlite3'
import * as schema from '@shared/constant/schema'
import { app } from 'electron'
import { dirname, join } from 'path'
import fs from 'fs'
import log from 'electron-log'

// 统一数据库文件位置（与 src/main/db/index.ts 一致的策略）
// 开发：项目根；生产：安装目录根
const baseDir = app.isPackaged ? dirname(process.execPath) : app.getAppPath()
const databasePathFromEnv = process.env.MAIN_VITE_DATABASE_URL
const relativeDbPath = databasePathFromEnv
  ? databasePathFromEnv.replace(/^\/+/, '')
  : 'db/database.sqlite'

const dbPath = join(baseDir, relativeDbPath)

// 确保目录存在
const dbDir = join(dbPath, '..')
if (!fs.existsSync(dbDir)) {
  fs.mkdirSync(dbDir, { recursive: true })
}

const sqlite = new Database(dbPath)

const drizzleLogger = {
  logQuery: (sql: string, params: any[] = []) => {
    const message = `Query: ${sql} => Params: [${params.join(', ')}]`
    log.info(message) // 同时输出到控制台和日志文件
  }
}

const orm: BetterSQLite3Database<typeof schema> = drizzle(sqlite, { logger: drizzleLogger, schema })
export default orm
